package pers.kw.server.sentinel.controller;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import pers.kw.protocol.R;

import java.util.ArrayList;
import java.util.List;

//@RestController
public class SentinelResourceController {

    private static final Logger log = LoggerFactory.getLogger(SentinelResourceController.class);


    //http://localhost:48010/testAspect/12
    @GetMapping("/testAspect/{id}")
// id   @SentinelResource(value = "testAspect",
//            fallback = "fallback", fallbackClass = CommonException.class,
//            blockHandler = "handleException", blockHandlerClass = CommonException.class
//    )
    public R testAspect(@PathVariable("id") Integer id) {
        if (Integer.compare(id, Integer.parseInt("0")) == -1) {
            throw new IllegalArgumentException("参数异常");
        }
        log.info("处理业务信息");
        return R.ok("测试注解方式限流正常");
    }


    //@PostConstruct
    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        //设置受保护的资源
        rule.setResource("testAspect");
        // 设置流控规则 QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        rule.setCount(1);
        rules.add(rule);
        // 加载配置好的规则
        FlowRuleManager.loadRules(rules);
    }
}
